/*
 * DetectMove.cpp
 *
 *  Created on: Nov 14, 2013
 *      Author: thanhkm
 */

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int maindm(int argc, char** argv)
{
    VideoCapture cap;
    if (argc > 1)
        cap.open(argv[1]);
    else
        cap.open(0);

    if (!cap.isOpened())
    {
        std::cerr << "Cannot read video. Try moving video file to sample directory." << std::endl;
        return -1;
    }

    initModule_video();
    setUseOptimized(true);
    setNumThreads(8);

    Ptr<BackgroundSubtractorGMG> fgbg = Algorithm::create<BackgroundSubtractorGMG>("BackgroundSubtractor.GMG");
    if (fgbg.empty())
    {
        std::cerr << "Failed to create BackgroundSubtractor.GMG Algorithm." << std::endl;
        return -1;
    }

    fgbg->set("initializationFrames", 10);
    fgbg->set("decisionThreshold", 0.99);

    Mat frame, fgmask, segm;
    Mat currframe, last;
    Mat background;

    cap >> last;
	last.copyTo(background);

    int i = 0;
    for (;;)
    {

    	//mine
//        cap >> lastframe;
//        waitKey(10);
        cap >> last;
//        if(i>100){
//        	last.copyTo(background);
//			i = 0;
//        }
//        i++;

        //----------OpenCV----------
        cap >> frame;
        if (frame.empty())
            break;
        (*fgbg)(frame, fgmask);

        dilate(fgmask, fgmask, Mat(), Point(-1, -1), 2);
        erode(fgmask, fgmask, Mat(), Point(-1, -1), 2);

        frame.copyTo(segm);

//        add(Scalar(255, 255, 255), frame, segm, fgmask);
		imshow("frame", frame);
		imshow("fgmask", fgmask);
        imshow("segm", segm);
        imshow("framelast", background);


        // introduce a delay
        // or press key to stop
        int c = waitKey(30);
        if (c == 'q' || c == 'Q' || (c & 255) == 27)
            break;
    }

    return 0;
}



